package handler

import (
	user_db "filestore/db"
	"filestore/util"
	"fmt"
	"net/http"
	"time"
)

// 注册

func SignInHandler(w http.ResponseWriter, r *http.Request) {

}
func RegisterHandler(w http.ResponseWriter, r *http.Request) {

	r.ParseForm()
	username := r.Form.Get("username")
	password := r.Form.Get("password")

	fmt.Println(username + password)
	//_, e := user_db.GetUserInfo(username)
	//if e!=nil {
	//	fmt.Println("查询数据库出错%s",e.Error())
	//	w.Write([]byte("注册时出错"))
	//	return
	//}
	isResult := user_db.UserSigenup(username, password)
	if !isResult {
		fmt.Println("插入数据库出错")
		w.Write([]byte("注册时出错"))
		return
	}

	w.Write([]byte("注册成功"))
}

// 登录
func LoginHandler(w http.ResponseWriter, r *http.Request) {

	if r.Method == http.MethodGet {
		// data, err := ioutil.ReadFile("./static/view/signin.html")
		// if err != nil {
		// 	w.WriteHeader(http.StatusInternalServerError)
		// 	return
		// }
		// w.Write(data)
		http.Redirect(w, r, "/static/view/signin.html", http.StatusFound)
		return
	}
	r.ParseForm()

	//if r.Method != http.MethodPost {
	//	w.Write([]byte("Method is not surrport"))
	//	return
	//}

	username := r.Form.Get("username")
	passwd := r.Form.Get("password")
	isSuccess := user_db.UserSignin(username, passwd)
	if !isSuccess {
		w.Write([]byte("login faild"))
		return
	}

	token := GenToken(username)
	user_db.UpdateToken(username, token)
	// 重定向首页

	resp := util.RespMsg{
		Code: 0,
		Msg:  "OK",
		Data: struct {
			Location string
			Username string
			Token    string
		}{
			Location: "http://" + r.Host + "/static/view/home.html",
			Username: username,
			Token:    token,
		},
	}
	w.Write(resp.JSONBytes())

}

// GenToken : 生成token
func GenToken(username string) string {
	// 40位字符:md5(username+timestamp+token_salt)+timestamp[:8]
	ts := fmt.Sprintf("%x", time.Now().Unix())
	tokenPrefix := util.MD5([]byte(username + ts + "_tokensalt"))
	return tokenPrefix + ts[:8]
}

// IsTokenValid : token是否有效
func IsTokenValid(token string) bool {
	if len(token) != 40 {
		return false
	}
	// TODO: 判断token的时效性，是否过期
	// TODO: 从数据库表tbl_user_token查询username对应的token信息
	// TODO: 对比两个token是否一致
	return true
}
